package com.xingmang.admin.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingmang.common.constant.PageEntity;
import com.xingmang.common.constant.ResponseData;
import com.xingmang.common.constant.ResultBean;
import com.xingmang.common.dto.admin.AppSettingInfoDTO;
import com.xingmang.common.dto.admin.AppSettingPageDTO;
import com.xingmang.common.dto.admin.AppSettingSaveDTO;
import com.xingmang.common.dto.admin.AppSettingUpdateDTO;
import com.xingmang.common.vo.admin.AppSettingPageVO;
import com.xingmang.db.entity.AppSetting;
import com.xingmang.db.entity.ThirdApp;
import com.xingmang.db.service.AppSettingDBService;
import com.xingmang.db.service.ThirdAppDBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @auther: hansom
 * @Version: 1.0
 * @create 2023/6/21 15:03
 */
@Service
@Slf4j
public class AppSettingService {

    @Resource
    private AppSettingDBService appSettingDBService;

    @Resource
    private ThirdAppDBService thirdAppDBService;

    public ResultBean<PageEntity<AppSettingPageVO>> page(AppSettingPageDTO dto) {
        Page<AppSetting> page = appSettingDBService.page(new Page<>(dto.getPagenum(), dto.getPagesize()),
                new LambdaQueryWrapper<AppSetting>()
                        .eq(dto.getAppId() != null, AppSetting::getAppId, dto.getAppId()));
        List<AppSettingPageVO> collect = page.getRecords().stream().map(appSetting -> {
            AppSettingPageVO vo = BeanUtil.copyProperties(appSetting, AppSettingPageVO.class);
            ThirdApp thirdApp = thirdAppDBService.getById(appSetting.getAppId());
            if (thirdApp != null) {
                vo.setAppName(thirdApp.getAppName());
            }
            return vo;
        }).collect(Collectors.toList());
        PageEntity<AppSettingPageVO> pageEntity = new PageEntity<>();
        BeanUtil.copyProperties(page,pageEntity);
        pageEntity.setRecords(collect);
        return ResponseData.success(pageEntity);
    }

    public ResultBean save(AppSettingSaveDTO dto) {
        AppSetting appSetting = BeanUtil.copyProperties(dto, AppSetting.class);
        appSettingDBService.save(appSetting);
        return ResponseData.success(null);
    }

    public ResultBean update(AppSettingUpdateDTO dto) {
        AppSetting appSetting = BeanUtil.copyProperties(dto, AppSetting.class);
        appSetting.setId(dto.getAppSettingId());
        appSettingDBService.updateById(appSetting);
        return ResponseData.success(null);
    }

    public ResultBean delete(AppSettingInfoDTO dto) {
        appSettingDBService.removeById(dto.getAppSettingId());
        return ResponseData.success(null);
    }
}
